package com.medicine.product.utils;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.ByteArrayOutputStream;
import java.util.Map;

/**
 * Create by YangKG
 * Date: 2020/12/22
 * Effect: 填充pdf表单域并返回新的pdf的字节数组,springboot下的用法
 */
public class ItextPdfUtils {

    public  byte[] pdfBytes(Map<String,String> map,byte[] bytes) throws Exception{
        PdfReader reader = new PdfReader(bytes);// 根据字节数组读取pdf模板
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, bos);
        AcroFields form = stamper.getAcroFields();
        BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
        form.addSubstitutionFont(bf);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            form.setField(entry.getKey(), entry.getValue());
        }
        stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
        stamper.close();
        return bos.toByteArray();
    }

    public static byte[] pdfBytes(Map<String,String> map,String path) throws Exception{
        PdfReader reader = new PdfReader(path);// 根据字节数组读取pdf模板
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, bos);
        AcroFields form = stamper.getAcroFields();
        BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
        form.addSubstitutionFont(bf);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            form.setField(entry.getKey(), entry.getValue());
        }
        stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
        stamper.close();
        return bos.toByteArray();
    }

}
